package com.mysoft.gfyx.marketdevelop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.gfyx.common.concurrency.CacheAgentService;
import com.mysoft.gfyx.common.time.TimeService;
import com.mysoft.gfyx.marketdevelop.controller.dto.inspect.ChartRequestDto;
import com.mysoft.gfyx.marketdevelop.controller.dto.inspect.PieResponseDto;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.DeveloperListRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.SqlApiResponseDto;
import com.mysoft.gfyx.marketdevelop.remoteService.RemoteCustomerService;
import com.mysoft.gfyx.marketdevelop.service.DeveloperService;
import com.mysoft.gfyx.marketdevelop.service.InspectDeveloperService;
import com.mysoft.gfyx.marketdevelop.service.LoadDataApiCommonService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class InspectDeveloperServiceImp extends BaseDataApiServiceImp implements InspectDeveloperService {

    @Autowired
    private DeveloperService developerService;

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Autowired
    private LoadDataApiCommonService loadDataApiCommonService;

    @Autowired
    private TimeService timeService;

    @Autowired
    private CacheAgentService cacheAgentService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Value("${tjdata.metrics.takeland}")
    private String metricTakeLand;

    public FieldsSetting loadFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("uuid");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "inspect_developer";
        fieldsSetting.getFields().add(new DataApiField("uuid", groupName, "RowID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_name", groupName, "拿地企业", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label", groupName, "拿地企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_developer_name", groupName, "顶级企业", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_company_type_label", groupName, "顶级公司类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "所在区域（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "所在区域（省）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "所在区域（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "所在区域（市）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("taken_land_number", groupName, "拿地数量（块）", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("latest_taken_land_date", groupName, "最新拿地时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("opened_trading_number", groupName, "项目开盘（个）", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("latest_opened_trading_date", groupName, "最新开盘时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("commence_permit_number", groupName, "项目开工（个）", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("latest_commence_permit_date", groupName, "最新开工时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("has_added", groupName, "是否已添加过客户", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("own_commence_permit", groupName, "在建项目数量", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("developer_activity_label", groupName, "业务活跃", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_ycg_certification", groupName, "平台认证", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_ycg_offline_business_connect", groupName, "供需对接会", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_top_100_label", groupName, "地产百强", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_new_decorate_expand_label", groupName, "新精装客群", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_new_land_usage_expand_label", groupName, "新住宅客群", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_new_area_expand_label", groupName, "新区域拓展", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("high_project_customers_label", groupName, "高端项目客群", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_province", groupName, "注册所在地（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_province_code", groupName, "注册所在地（省）code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_city", groupName, "注册所在地（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_city_code", groupName, "注册所在地（市）code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_level_tag", groupName, "企业等级", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tags_set", groupName, "企业标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_province_and_city", groupName, "开发商所在省份城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("land_usage", groupName, "土地用途", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_score", groupName, "好客户得分", FieldType.Int));
        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadData(LoadDataParams options) {
        Object provinceCode = options.getOptions().getContext().get("province_code");
        Object cityCode = options.getOptions().getContext().get("city_code");
        Object timeBegin = options.getOptions().getContext().get("time_begin");
        Object timeEnd = options.getOptions().getContext().get("time_end");

        DeveloperListRequestDto dto = new DeveloperListRequestDto();
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());

        dto.setPageNum(options.getPageIndex() + 1);
        dto.setPageSize(options.getPageSize());
        if (provinceCode != null) dto.setProvince_code(provinceCode.toString());
        if (cityCode != null) dto.setCity_code(cityCode.toString());
        if (timeBegin != null) dto.setTime_begin(timeBegin.toString());
        if (timeEnd != null) dto.setTime_end(timeEnd.toString());

        Object developerName = loadDataApiCommonService.getValueByConditionField(options.getOptions().getFilters(), "developer_name");
        if (developerName != null) dto.setDeveloper_name("%" + developerName.toString() + "%");

        SqlApiResponseDto res = getDeveloperDataService.getDeveloperList(dto);

        if (res.getData() == null || res.getData().getTotalNum() == 0) {
            return new ListDataResult();
        }

        // 获取是否添加过客户
        List<String> creditCodes = res.getData().getRows().stream().map(p -> p.get("organizing_code").toString()).collect(Collectors.toList());
        Set<String> haveAdded = remoteCustomerService.isAdded(creditCodes);

        // 获取好客户得分
        // 好客户模型注释掉，目前不使用，如果重新启用，得优化 open search 的接口性能，目前超过 2000 报错
        //  HashMap<String, Integer> developerScoreMap = developerService.getDeveloperScoreMapByCreditCodeList(creditCodes);
        ListDataResult listDataResult = new ListDataResult();
        res.getData().getRows().forEach(r -> {
            if (r.get("latest_taken_land_date") != null) {
                String latestTakenLandDate = timeService.convertTimeFormat(r.get("latest_taken_land_date").toString(), "yyyyMMddHHmmss", "yyyy-MM-dd");
                r.put("latest_taken_land_date", latestTakenLandDate);
            }
            if (r.get("latest_opened_trading_date") != null) {
                String latestOpenedTradingDate = timeService.convertTimeFormat(r.get("latest_opened_trading_date").toString(), "yyyyMMddHHmmss", "yyyy-MM-dd");
                r.put("latest_opened_trading_date", latestOpenedTradingDate);
            }
            if (r.get("latest_commence_permit_date") != null) {
                String latestCommenceDate = timeService.convertTimeFormat(r.get("latest_commence_permit_date").toString(), "yyyyMMddHHmmss", "yyyy-MM-dd");
                r.put("latest_commence_permit_date", latestCommenceDate);
            }
            if (r.get("taken_land_number") != null) {
                r.put("taken_land_number", Integer.valueOf(r.getOrDefault("taken_land_number", 0).toString()));
            }
            if (r.get("opened_trading_number") != null) {
                r.put("opened_trading_number", Integer.valueOf(r.getOrDefault("opened_trading_number", 0).toString()));
            }
            if (r.get("commence_permit_number") != null) {
                r.put("commence_permit_number", Integer.valueOf(r.getOrDefault("commence_permit_number", 0).toString()));
            }
            if (r.get("city") != null && r.get("city").equals(r.getOrDefault("province", ""))) r.put("city", "");
            r.putIfAbsent("top_organizing_code", "");
            r.putIfAbsent("top_developer_name", "");
            r.putIfAbsent("top_company_type_label", "");

            // 是否添加过
            if (r.get("organizing_code") != null) {
                int hasAdded = haveAdded.contains(r.get("organizing_code").toString()) ? 1 : 0;
                r.put("has_added", hasAdded);
            }

            // 在建项目数量，目前不使用该参数作数量统计
            if (r.get("building_project_equity_uid") == null) {
                r.put("building_project_number", r.get("building_project_cnt"));
            } else {
                r.put("building_project_number", countBuildingProject(r.getOrDefault("building_project_equity_uid", "").toString()));
            }
            //企业等级(拼接)
            List<String> companyLevel = new ArrayList<>();
            if (r.get("developer_activity_label") != null && !r.get("developer_activity_label").equals("")) {
                companyLevel.add(r.get("developer_activity_label").toString());
            }
            if (r.get("is_ycg_certification") != null && !r.get("is_ycg_certification").equals("")) {
                companyLevel.add(r.get("is_ycg_certification").toString());
            }
            if (r.get("is_ycg_offline_business_connect") != null && !r.get("is_ycg_offline_business_connect").equals("")) {
                companyLevel.add(r.get("is_ycg_offline_business_connect").toString());
            }
            r.put("company_level_tag", companyLevel.stream().map(String::valueOf).collect(Collectors.joining(",")));
            //企业标签(拼接)
            List<String> tagsSet = new ArrayList<>();
            if (r.get("developer_top_100_label") != null && !r.get("developer_top_100_label").equals("")) {
                tagsSet.add(r.get("developer_top_100_label").toString());
            }
            if (r.get("is_new_decorate_expand_label") != null && !r.get("is_new_decorate_expand_label").equals("")) {
                tagsSet.add(r.get("is_new_decorate_expand_label").toString());
            }
            if (r.get("is_new_land_usage_expand_label") != null && !r.get("is_new_land_usage_expand_label").equals("")) {
                tagsSet.add(r.get("is_new_land_usage_expand_label").toString());
            }
            if (r.get("is_new_area_expand_label") != null && !r.get("is_new_area_expand_label").equals("")) {
                tagsSet.add(r.get("is_new_area_expand_label").toString());
            }
            if (r.get("high_project_customers_label") != null && !r.get("high_project_customers_label").equals("")) {
                tagsSet.add(r.get("high_project_customers_label").toString());
            }
            r.put("tags_set", tagsSet.stream().map(String::valueOf).collect(Collectors.joining(",")));
            //开发商所在地(拼接)
            String provinceName;
            if (r.get("developer_province") != null && r.get("developer_city") != null) {
                provinceName = r.getOrDefault("developer_province", "").equals(r.getOrDefault("developer_city", "")) ? "" : r.getOrDefault("developer_province", "").toString();
            } else {
                provinceName = "";
            }
            String cityName = r.get("developer_city") == null ? "" : r.getOrDefault("developer_city", "").toString();
            r.put("developer_province_and_city", provinceName + cityName);

            // 好客户模型注释掉，目前不使用，如果重新启用，得优化 open search 的接口性能，目前超过 2000 报错
            r.put("developer_score", 0);
//            if (r.get("organizing_code") != null) {
//                Integer score = developerScoreMap.get(r.get("organizing_code").toString());
//                if (score != null) {
//                    r.put("developer_score", score);
//                } else {
//                    r.put("developer_score", 0);
//                }
//            }

        });
        listDataResult.setTotal(res.getData().getTotalNum());
        listDataResult.setData(res.getData().getRows());
        return listDataResult;
    }

    public PieResponseDto developerTypePie(ChartRequestDto dto) {

        String cacheKey = "DEVELOPER_TYPE_PIE:" + DigestUtils.md5Hex(dto.toString());
        PieResponseDto pieResponseDto = cacheAgentService.getCachedData(cacheKey);

        if (pieResponseDto != null) {
            return pieResponseDto;
        }

        dto.setPageNum(1);
        dto.setPageSize(100);
        SqlApiResponseDto res = getDeveloperDataService.getDeveloperTypePie(dto);

        pieResponseDto = new PieResponseDto();
        pieResponseDto.loadData(res);

        cacheAgentService.setCacheData(cacheKey, pieResponseDto);

        return pieResponseDto;
    }

    protected int countBuildingProject(String buildingProjectJson) {
        Set<String> buildingProjectSet = new HashSet<>();

        JSONArray projects = JSON.parseArray(buildingProjectJson);
        projects.forEach(l -> {
            List<String> ts = JSON.parseArray(JSON.toJSONString(l), String.class);
            ts.forEach(t -> {
                buildingProjectSet.add(t);
            });
        });

        return buildingProjectSet.size();
    }
}
